﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrankShaftAnalysisSystem
{
    public class DataStorage
    {
        public string[] PositionMark = new string[8];
        public class CurvePoint
        {
            public CurvePoint()
            {
            }
            public string PointMark { get; set; }
            public double Z { get; set; }
            public double p { get; set; }
            public double Phi { get; set; }
            public double Pen1 { get; set; }
            public double Pen2 { get; set; }
            public double Pen3 { get; set; }
            public DateTime Stamp { get; set; }
        }

        public ObservableCollection<CurvePoint> Clouds { get; set; }
        public static string uuid;
        public DataStorage(string id)
        {
            Clouds = new ObservableCollection<CurvePoint>();
            for (int i = 0; i < PositionMark.Length; i++)
                PositionMark[i] = $"P{i}";
            uuid = id;
        }

        public static bool FileExisting()
        {
            var path = Path.Combine("./Results", uuid + ".csv");
            return File.Exists(path);
        }

        public static string GetCsvPath()
        {
            var path = Path.Combine("./Results", uuid + ".csv");
            return path;
        }

        public string PointToString(int i)
        {
            var p = Clouds[i];
            var ret = $"{i},{p.PointMark},{p.p},{p.Z},{p.Phi},{p.Pen1},{p.Pen2},{p.Pen3},{p.Stamp:yyyy-MM-dd HH:mm:ss.ff}";
            return ret;
        }

        public void Dispose()
        {
            Clouds?.Clear();
        }

        public void SaveResults()
        {
            var path = Path.Combine("./Results", uuid + ".csv");
            Directory.CreateDirectory("./Results");
            using(var wr = new StreamWriter(path, false))
            {
                try
                {
                    wr.WriteLine($"PartName:{uuid}");
                    wr.WriteLine("index,Marker,p,Z,phi,pen1,pen2,pen3,stamp");
                    for (int i = 0; i < Clouds.Count; i++)
                    {
                        wr.WriteLine(PointToString(i));
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
                finally
                {
                    wr.Close();
                    wr.Dispose();
                }
            }
        }
    }
}
